//
//  Language.m
//
//  Created by cktim852 on 21/03/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "HTTPConnectionUtility.h"
#import "Constants.h"
#import "DeviceUtil.h"
#import "HashUtility.h"
#import "HTTPUtil.h"

// Const variables of http connection tag ID.
NSString * const kGSPProxyConnectTag = @"gspProxyConnect";
NSString * const kMultipleGSPProxyConnectTag = @"multipleGspProxyConnect";
@implementation HTTPConnectionUtility

@synthesize httpConnection;
@synthesize receivedData;
@synthesize currentChallenge;
@synthesize timeoutCounter;
@synthesize tagId;
/* WDT enhancement start */
@synthesize taskId;
@synthesize callback;
/* WDT enhancement end */
@synthesize expectedContentLength;

//Function SSL Pinning Country Configuration
//Start:by Winger Ye 2015-06-21
@synthesize alwaysValidateSSLPinning;
//End


// 2013-12-19, Nathan, Core Enhancement for HSBCNet -end
- (void)dealloc
{
	[httpConnection cancel];
    [httpConnection release];
    [receivedData release];
    [currentChallenge release];
    [tagId release];
    /* WDT enhancement start */
    [taskId release];
    [callback release];
    /* WDT enhancement end */
    [super dealloc];
}

+ (NSMutableURLRequest*)createFormRequestWithURLString:(NSString*)urlpath
                                 requestParametersInfo:(NSDictionary*)requestParametersInfo
                                         requestMethod:(NSString*)method
                                        needHSBCHeader:(BOOL)needHSBCHeader
{
    // check params
    if (urlpath == nil)
    {
        return nil;
    }
    
    NSURL *url = nil;
    NSMutableURLRequest *urlRequest = nil;
    
    // urlencode and normalize parameters
    NSString *normalizedQueryString = [[self class] normalizeRequestParametersInfo:requestParametersInfo];
    
    if ([[method uppercaseString] isEqualToString:@"POST"])
    {
        // POST
        
        url =[NSURL URLWithString:urlpath];
        DebugLog(@"url is %@",[url absoluteString]);
        DebugLog(@"POST method and post body %@", normalizedQueryString);
        
        urlRequest = [NSMutableURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:60.0];
        
        [urlRequest setHTTPMethod:@"POST"];
        [urlRequest setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [urlRequest setHTTPBody:[normalizedQueryString dataUsingEncoding:NSUTF8StringEncoding]];
    }
    else
    {
        // GET
        
        // check url path have '?' or not
        if( [urlpath rangeOfString:@"?"].location == NSNotFound )
        {
            url = [NSURL URLWithString:[urlpath stringByAppendingFormat:@"?%@",normalizedQueryString]];
        }
        else
        {
            url = [NSURL URLWithString:[urlpath stringByAppendingFormat:@"&%@",normalizedQueryString]];
        }
        
        DebugLog(@"url is %@",[url absoluteString]);
        DebugLog(@"GET method");
        
        urlRequest=[NSMutableURLRequest requestWithURL:url
                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                       timeoutInterval:60.0];
        
        [urlRequest setHTTPMethod:@"GET"];  // default GET
        [urlRequest setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    }
    

    return urlRequest;
}

+ (NSString *)normalizeRequestParametersInfo:(NSDictionary *)requestParametersInfo
{
    NSMutableArray *parametersArray = [NSMutableArray array];
    for (NSString *key in requestParametersInfo)
    {
        id paramValue = [requestParametersInfo valueForKey:key];
        if ([paramValue isKindOfClass:[NSArray class]])
        {
            for (id value in paramValue)
            {
                [HTTPConnectionUtility normalizeKeyValue:key value:value parametersArray:parametersArray];
            }
        }
        else if ([paramValue isKindOfClass:[NSString class]]||[paramValue isKindOfClass:[NSNumber class]])
        {
            [HTTPConnectionUtility normalizeKeyValue:key value:paramValue parametersArray:parametersArray];
        }
        
    }
    
    return [parametersArray componentsJoinedByString:@"&"];
}

+ (void)normalizeKeyValue:(NSString *)key value:(id)paramValue parametersArray:(NSMutableArray *)parametersArray
{
    if ([paramValue isKindOfClass:[NSString class]])
    {
        // SDK encoding
        // NSString *encodeValue = [paramValue stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        // enhancement URLEncoding
        NSString *encodeValue = [HTTPConnectionUtility encodeURL:paramValue];
        [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, encodeValue]];
    }
    else if ([paramValue isKindOfClass:[NSNumber class]])
    {
        // TBC
        NSString *valueString = [paramValue stringValue];
        [parametersArray addObject:[NSString stringWithFormat:@"%@=%@", key, valueString]];
    }
    else
    {
        DebugLog(@"param value is not string or number, so skip it.");
        DebugLog(@"param key is %@, value is %@", key, paramValue);
    }
}

+ (NSString*)encodeURL:(NSString *)string
{
    //  ASIFormDataRequest.m
    //  Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
    //  CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`")
    
    NSString *newString = [NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                     (CFStringRef)string,
                                                                                     NULL,
                                                                                     CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),
                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)))
                           autorelease];
    if (newString)
    {
        return newString;
    }
    return nil;
}


@end
